from flask import Blueprint, request, jsonify
from .Cmod import *
from .Cmod_pic import *
from .Cmod_user import *
from .Cmod_express import *

blue_chat = Blueprint('chat', __name__)


# 渲染某用户和用户之间的聊天
@blue_chat.route('/api/chat/user', methods=['POST', 'GET'])
def get_chat_user():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    # print(data)
    user_id = data.get('user_id')
    user_for = data.get('for_id')
    # 查询数据库中的所有聊天数据
    discords1 = Discord.query.filter_by(discord_user=user_id, discord_reception=user_for).all()
    discords2 = Discord.query.filter_by(discord_user=user_for, discord_reception=user_id).all()

    discord1 = discords1 + discords2
    for discord_now1 in discord1:
        user_now = Users.query.filter_by(user_id=discord_now1.discord_user).first()
        pic_now = Picture.query.filter_by(picture_ob_type='user', picture_object=discord_now1.discord_user).first()
        discord_data = [
            {
                'discord_id': discord_now1.discord_id,
                'discord_user': discord_now1.discord_user,
                'discord_reception': discord_now1.discord_reception,
                'discord_text': discord_now1.discord_text,
                'discord_time': discord_now1.discord_time.strftime('%Y-%m-%d %H:%M:%S'),
                'user_name': user_now.user_name,
                'user_pic': pic_now.picture_address
            }
        ]
    for res_now in discord1:
        if res_now.discord_state:
            res_now.discord_state = False
    db.session.commit()
    response = {
        'data': discord_data
    }

    print("聊天数据发送", response)
    return jsonify(response), 200


# 用户进入聊天窗口
@blue_chat.route('/api/chat', methods=['POST', 'GET'])
def get_chat():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    # print(data)
    user_id = data.get('user_id')
    attention_now = AttentionFan.query.filter_by(af_parent=user_id).all()
    attention_data = [{
        'attention_id': att.af_child,
    } for att in attention_now]
    for item in attention_data:
        avatar = (db.session.query(Picture).filter_by(
            picture_ob_type='user',
            picture_object=item['attention_id']
        ).first())
        if avatar:
            item['picture'] = avatar.picture_address

    fans_now = AttentionFan.query.filter_by(af_child=user_id).all()
    fans_data = [{
        'fans_id': fan.af_parent,
    } for fan in fans_now]

    for item in fans_data:
        avatar = (db.session.query(Picture).filter_by(
            picture_ob_type='user',
            picture_object=item['fans_id']
        ).first())
        if avatar:
            item['picture'] = avatar.picture_address

    # 首先，找出所有关注当前用户（user_id）的用户列表
    followers = (db.session.query(AttentionFan.af_parent)
                 .filter_by(af_child=user_id)
                 .all())

    # 然后，找出当前用户（user_id）关注的所有用户列表
    following = (db.session.query(AttentionFan.af_child)
                 .filter_by(af_parent=user_id)
                 .all())

    # 将查询结果转换为用户ID的集合，以便进行交集操作
    followers_ids = {item.af_parent for item in followers}
    following_ids = {item.af_child for item in following}

    # 找出两个集合的交集，即互相关注的用户ID
    mutual_ids = followers_ids.intersection(following_ids)

    # 现在我们有了互相关注的用户ID集合，我们可以查询这些用户的头像信息
    mutual_data = []
    for mutual_id in mutual_ids:
        picture = (db.session.query(Picture)
                   .filter_by(picture_ob_type='user', picture_object=mutual_id)
                   .first())
        if picture:
            mutual_data.append({
                'attention_id': mutual_id,
                'picture': picture.picture_address
            })
    discord = Discord.query.filter_by(discord_user=user_id,
                                      discord_state=False).all()
    discord_data = [
        {
            'discord_id': discord_now.discord_id,
            'discord_user': discord_now.discord_user,
            'discord_reception': discord_now.discord_reception,
            'discord_text': discord_now.discord_text,
            'discord_time': discord_now.discord_time
        } for discord_now in discord
    ]
    user_data = []
    user_id1 = [item['attention_id'] for item in attention_data if
                'attention_id' in item and item['attention_id']]
    user_id2 = [item.get('fans_id') for item in fans_data
                if item.get('fans_id') is not None]
    user_id3 = [item['attention_id'] for item in mutual_data]
    users_id = user_id1 + user_id2 + user_id3
    unique_user_ids = set(users_id)
    for user_id_now in unique_user_ids:
        user_now = Users.query.filter_by(user_id=user_id_now).first()
        user_data.append({
            'user_id': user_now.user_id,
            'user_name': user_now.user_name,
            'user_introduce': user_now.user_introduce,
            'user_attention': user_now.user_attention,
            'user_fan': user_now.user_fan
        })
    response = {
        'attention_data': attention_data,
        'fans_data': fans_data,
        'discord_data': discord_data,
        'mutual_ids_data': mutual_data,
        'user_list': user_data
    }
    return jsonify(response), 200
